package com.alipay.rebate.shop.utils;

import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.exceptoin.TpwdGenerateFailException;
import com.alipay.rebate.shop.helper.AppSettingsHelper;
import com.alipay.rebate.shop.model.AppSettings;
import com.alipay.rebate.shop.model.Orders;
import com.alipay.rebate.shop.model.RefundOrders;
import com.alipay.rebate.shop.pojo.taobao.DgMaterialRequest;
import com.alipay.rebate.shop.pojo.taobao.DgOptimusMaterialRequest;
import com.alipay.rebate.shop.pojo.taobao.ItemInfoRequest;
import com.alipay.rebate.shop.pojo.taobao.RefundOrderRequest;
import com.alipay.rebate.shop.pojo.taobao.TkOrderRequest;
import com.alipay.rebate.shop.pojo.taobao.TkOrderRsponse;
import com.alipay.rebate.shop.pojo.taobao.TpwdRequest;
import com.alipay.rebate.shop.scheduler.TypeTkStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.util.StringUtils;
import com.taobao.api.internal.util.WebUtils;
import com.taobao.api.request.TbkDgMaterialOptionalRequest;
import com.taobao.api.request.TbkDgOptimusMaterialRequest;
import com.taobao.api.request.TbkItemInfoGetRequest;
import com.taobao.api.request.TbkOrderDetailsGetRequest;
import com.taobao.api.request.TbkRelationRefundRequest;
import com.taobao.api.request.TbkRelationRefundRequest.TopApiRefundRptOption;
import com.taobao.api.request.TbkScPublisherInfoSaveRequest;
import com.taobao.api.request.TbkTpwdCreateRequest;
import com.taobao.api.response.TbkDgMaterialOptionalResponse;
import com.taobao.api.response.TbkDgOptimusMaterialResponse;
import com.taobao.api.response.TbkItemInfoGetResponse;
import com.taobao.api.response.TbkOrderDetailsGetResponse;
import com.taobao.api.response.TbkOrderDetailsGetResponse.PublisherOrderDto;
import com.taobao.api.response.TbkRelationRefundResponse;
import com.taobao.api.response.TbkScPublisherInfoSaveResponse;
import com.taobao.api.response.TbkTpwdCreateResponse;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TaobaoUtil {

    private final static Logger logger = LoggerFactory.getLogger(TaobaoUtil.class);

    public static  String APPKEY = "27666797";
    public static  String APPSECRET = "d128f43ef975e70b4594699c53d0d9e7";
    public static final String RELATION_INVITOR_CODE = "H6HYGX";
//    public static final String SPECIAL_INVITOR_CODE = "AAV96T";
    public static final String SPECIAL_INVITOR_CODE = "3MC8UC";
    public static final String PID = "mm_196240035_620000087_109205150467";
    public static final Long AD_ZONE_ID = 109205150467L;

    private static final Long TKSTATUS_ALL = 1L;
    public static final Long TKSTATUS_AC = 3L;
    public static final Long TKSTATUS_PAID = 12L;
    public static final Long TKSTATUS_OVERDUE = 13L;
    public static final Long TKSTATUS_DONE = 14L;

    private static final Long SCENE_NORMAL = 1L;
    private static final Long SCENE_RELATION = 2L;
    private static final Long SCENE_SPECIAL = 3L;

    private static Gson gson = new GsonBuilder().create();
    static ObjectMapper objectMapper = new ObjectMapper();

    private static void getAppKeyAndSecred(){
        AppSettings appSettings = AppSettingsHelper.getAppSettings();
        APPKEY = appSettings.getTaobaoAppKey();
        APPSECRET = appSettings.getTaobaoAppSecret();
        logger.debug("APPKEY get from db is : {}",APPKEY);
        logger.debug("APPSECRET get from db is : {}",APPSECRET);
    }

    // 获取通用物料
    public static TbkDgMaterialOptionalResponse getDgMaterial(
        DgMaterialRequest commonMaterialRequest) throws ApiException{
        getAppKeyAndSecred();
        String url = "http://gw.api.taobao.com/router/rest";
        TaobaoClient client = new DefaultTaobaoClient(url, APPKEY, APPSECRET);
        TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
        req.setStartDsr(commonMaterialRequest.getStart_dsr());
        req.setPageSize(commonMaterialRequest.getPage_size());
        req.setPageNo(commonMaterialRequest.getPage_no());
        req.setPlatform(commonMaterialRequest.getPlatform());
        req.setEndTkRate(commonMaterialRequest.getEnd_tk_rate());
        req.setStartTkRate(commonMaterialRequest.getStart_tk_rate());
        req.setEndPrice(commonMaterialRequest.getEnd_price());
        req.setStartPrice(commonMaterialRequest.getStart_price());
        req.setIsOverseas(commonMaterialRequest.getIs_overseas());
        req.setIsTmall(commonMaterialRequest.getIs_tmall());
        req.setSort(commonMaterialRequest.getSort());
        req.setItemloc(commonMaterialRequest.getItemloc());
        req.setCat(commonMaterialRequest.getCat());
        req.setQ(commonMaterialRequest.getQ());
        req.setMaterialId(commonMaterialRequest.getMaterial_id());
        req.setHasCoupon(commonMaterialRequest.getHas_coupon());
        req.setAdzoneId(commonMaterialRequest.getAdzone_id());
        req.setNeedFreeShipment(commonMaterialRequest.getNeed_free_shipmen());
        req.setNeedPrepay(commonMaterialRequest.getNeed_prepay());
        req.setIncludePayRate30(commonMaterialRequest.getInclude_pay_rate_30());
        req.setIncludeGoodRate(commonMaterialRequest.getInclude_good_rate());
        req.setIncludeRfdRate(commonMaterialRequest.getInclude_rfd_rate());
        req.setNpxLevel(commonMaterialRequest.getNpx_level());
        req.setEndKaTkRate(commonMaterialRequest.getEnd_ka_tk_rate());
        req.setStartKaTkRate(commonMaterialRequest.getStart_ka_tk_rate());
        req.setDeviceEncrypt(commonMaterialRequest.getDevice_encrypt());
        req.setDeviceValue(commonMaterialRequest.getDevice_value());
        req.setDeviceType(commonMaterialRequest.getDevice_type());
        TbkDgMaterialOptionalResponse rsp = client.execute(req);
        return  rsp;
    }

    // 获取通用物料（导购）
    public static TbkDgOptimusMaterialResponse getDgOptimusMaterial(DgOptimusMaterialRequest commonMaterialGuideRequest){
        try {
            getAppKeyAndSecred();
            String url = "http://gw.api.taobao.com/router/rest";
            TaobaoClient client = new DefaultTaobaoClient(url, APPKEY, APPSECRET);
            TbkDgOptimusMaterialRequest req = new TbkDgOptimusMaterialRequest();
            req.setPageSize(commonMaterialGuideRequest.getPage_size());
            req.setAdzoneId(AD_ZONE_ID);
            req.setPageNo(commonMaterialGuideRequest.getPage_no());
            req.setMaterialId(commonMaterialGuideRequest.getMaterial_id());
            req.setDeviceValue(commonMaterialGuideRequest.getDevice_value());
            req.setDeviceEncrypt(commonMaterialGuideRequest.getDevice_encrypt());
            req.setDeviceType(commonMaterialGuideRequest.getDevice_type());
            req.setContentId(commonMaterialGuideRequest.getContent_id());
            req.setContentSource(commonMaterialGuideRequest.getContent_source());
            req.setItemId(commonMaterialGuideRequest.getItem_id());
            TbkDgOptimusMaterialResponse rsp = client.execute(req);
            System.out.println(rsp.getBody());
            return rsp;
        }catch (ApiException ex){
            throw new BusinessException(StatusCode.INTERNAL_ERROR);
        }
    }

    // 获取订单
    public static TbkOrderDetailsGetResponse getOrder(TkOrderRequest orderRequest) {
      try {
        getAppKeyAndSecred();
        String url = "http://gw.api.taobao.com/router/rest";
        TaobaoClient client = new DefaultTaobaoClient(url, APPKEY , APPSECRET);
        TbkOrderDetailsGetRequest req = new TbkOrderDetailsGetRequest();
        req.setQueryType(orderRequest.getQuery_type());
        req.setPositionIndex(orderRequest.getPosition_index());
        req.setPageSize(orderRequest.getPage_size());
        req.setMemberType(orderRequest.getMember_type());
        req.setTkStatus(orderRequest.getTk_status());
        req.setEndTime(orderRequest.getEnd_time());
        req.setStartTime(orderRequest.getStart_time());
        req.setJumpType(orderRequest.getJump_type());
        req.setPageNo(orderRequest.getPage_no());
        req.setOrderScene(orderRequest.getOrder_scene());
        TbkOrderDetailsGetResponse rsp = client.execute(req);
        System.out.println(rsp.getBody());
        return rsp;
      }catch (ApiException ex){
        ex.printStackTrace();
      }
      return null;
    }

    public static TbkRelationRefundResponse getRefundOrder(RefundOrderRequest request){
        try {
            getAppKeyAndSecred();
            String url = "http://gw.api.taobao.com/router/rest";
            TaobaoClient client = new DefaultTaobaoClient(url, APPKEY, APPSECRET);
            TbkRelationRefundRequest req = new TbkRelationRefundRequest();
            TopApiRefundRptOption obj1 = new TopApiRefundRptOption();
            obj1.setPageSize(request.getPageSize());
            obj1.setSearchType(request.getSearchType());
            obj1.setRefundType(request.getRefundType());
            obj1.setStartTime(StringUtils.parseDateTime(request.getStartTime()));
            obj1.setPageNo(request.getPageNo());
            obj1.setBizType(request.getBizType());
            req.setSearchOption(obj1);
            TbkRelationRefundResponse rsp = client.execute(req);
            logger.debug(gson.toJson(rsp));
            return rsp;
        }catch (ApiException ex){
            ex.printStackTrace();
        }
        return null;
    }

    public static TkOrderRsponse getOrdersByStatusAndType(
        TypeTkStatus tkStatus,
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){
        if(tkStatus == TypeTkStatus.RELATION_PAID){
            return getRelationPaidOrders(startTime,endTime,pageNo,positionIndex);
        }
        if(tkStatus == TypeTkStatus.RELATION_ACCOUNTING){
            return getRelationAcOrders(startTime,endTime,pageNo,positionIndex);
        }
        if(tkStatus == TypeTkStatus.RELATION_COMPLETE){
            return getRelationDoneOrders(startTime,endTime,pageNo,positionIndex);
        }
        if(tkStatus == TypeTkStatus.RELATION_OVERDUE){
            return getRelationODOrders(startTime,endTime,pageNo,positionIndex);
        }
        if(tkStatus == TypeTkStatus.NORMAL_PAID){
            return getNormalPaidOrders(startTime,endTime,pageNo,positionIndex);
        }
        if(tkStatus == TypeTkStatus.NORMAL_ACCOUNTING){
            return getNormalAcOrders(startTime,endTime,pageNo,positionIndex);
        }
        if(tkStatus == TypeTkStatus.NORMAL_COMPLETE){
            return getNormalDoneOrders(startTime,endTime,pageNo,positionIndex);
        }
        if(tkStatus == TypeTkStatus.NORMAL_OVERDUE){
            return getNormalODOrders(startTime,endTime,pageNo,positionIndex);
        }
        if(tkStatus == TypeTkStatus.SPECIAL_PAID){
            return getSpecialPaidOrders(startTime,endTime,pageNo,positionIndex);
        }
        if(tkStatus == TypeTkStatus.SPECIAL_ACCOUNTING){
            return getSpecialAcOrders(startTime,endTime,pageNo,positionIndex);
        }
        if(tkStatus == TypeTkStatus.SPECIAL_COMPLETE){
            return getSpecialDoneOrders(startTime,endTime,pageNo,positionIndex);
        }
        if(tkStatus == TypeTkStatus.SPECIAL_OVERDUE){
            return getSpecialODOrders(startTime,endTime,pageNo,positionIndex);
        }
        return null;
    }

    // 渠道付款订单
    public static TkOrderRsponse getRelationPaidOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_RELATION,TKSTATUS_PAID,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return convertToOrdersList(rsp);

    }

    // 渠道结算订单
    public static TkOrderRsponse getRelationAcOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ) {

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_RELATION,TKSTATUS_AC,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return  convertToOrdersList(rsp);

    }

    // 渠道完成订单
    public static TkOrderRsponse getRelationDoneOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_RELATION,TKSTATUS_DONE,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return  convertToOrdersList(rsp);

    }

    // 渠道失效订单
    public static TkOrderRsponse getRelationODOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_RELATION,TKSTATUS_OVERDUE,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return  convertToOrdersList(rsp);

    }

    // 常规付款订单
    public static TkOrderRsponse getNormalPaidOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_NORMAL,TKSTATUS_PAID,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return convertToOrdersList(rsp);

    }

    // 常规结算订单
    public static TkOrderRsponse getNormalAcOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_NORMAL,TKSTATUS_AC,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return  convertToOrdersList(rsp);

    }

    // 常规完成订单
    public static TkOrderRsponse getNormalDoneOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_NORMAL,TKSTATUS_DONE,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return  convertToOrdersList(rsp);

    }

    // 常规失效订单
    public static TkOrderRsponse getNormalODOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_NORMAL,TKSTATUS_OVERDUE,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return  convertToOrdersList(rsp);

    }

    // 会员运营付款订单
    public static TkOrderRsponse getSpecialPaidOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_SPECIAL,TKSTATUS_PAID,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return convertToOrdersList(rsp);

    }

    // 会员运营结算订单
    public static TkOrderRsponse getSpecialAcOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_SPECIAL,TKSTATUS_AC,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return  convertToOrdersList(rsp);

    }

    // 会员运营完成订单
    public static TkOrderRsponse getSpecialDoneOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_SPECIAL,TKSTATUS_DONE,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return  convertToOrdersList(rsp);

    }

    // 会员运营失效订单
    public static TkOrderRsponse getSpecialODOrders(
        String startTime,
        String endTime,
        Long pageNo,
        String positionIndex
    ){

        TkOrderRequest req = buildOrderRequest(startTime,endTime,pageNo,
            SCENE_SPECIAL,TKSTATUS_OVERDUE,positionIndex);
        TbkOrderDetailsGetResponse rsp = getOrder(req);
        return  convertToOrdersList(rsp);

    }

    private static TkOrderRequest buildOrderRequest(
        String startTime,
        String endTime,
        Long pageNo,
        Long orderScene,
        Long tkStatus,
        String positionIndex
    ){
        TkOrderRequest orderRequest = new TkOrderRequest();
        orderRequest.setStart_time(startTime);
        orderRequest.setEnd_time(endTime);
        orderRequest.setPage_no(pageNo);
        orderRequest.setPage_size(100L);
        orderRequest.setOrder_scene(orderScene);
        orderRequest.setTk_status(tkStatus);
        orderRequest.setPosition_index(positionIndex);
        // 付款或者失效订单，按照订单创建时间查询
        if(tkStatus == 12L || tkStatus == 13L){
            orderRequest.setQuery_type(2L);
        }
        // 结算或者确认收货订单，按照订单结算时间查询
        if(tkStatus == 3L || tkStatus == 14L){
            orderRequest.setQuery_type(3L);
        }
        return orderRequest;
    }

    private static TkOrderRsponse convertToOrdersList(TbkOrderDetailsGetResponse rsp){

        TkOrderRsponse ordersResponse = buildDefaultTkRsp();

        List<Orders> ordersList = new ArrayList<>();
        if(rsp == null || rsp.getData() == null ||
            ListUtil.isEmptyList(rsp.getData().getResults())){
            return ordersResponse;
        }

        ordersResponse.setHas_next(rsp.getData().getHasNext());
        ordersResponse.setPosition_index(rsp.getData().getPositionIndex());

        List<PublisherOrderDto> nTbkOrders = rsp.getData().getResults();
        for(PublisherOrderDto publisherOrderDto: nTbkOrders){
            Orders orders = convertToOrders(publisherOrderDto);
            ordersList.add(orders);
        }

        ordersResponse.setData(ordersList);
        return ordersResponse;
    }

    // 渠道维权订单
    public static List<RefundOrders> getRelationRefundOrders(
        String startTime,
        Long pageNo
    ){

        RefundOrderRequest req = buildRefundOrderRequest(startTime,pageNo,1L);
        TbkRelationRefundResponse rsp = getRefundOrder(req);
        return  convertToRefundOrdersList(rsp);

    }

    // 渠道维权订单
    public static List<RefundOrders> getSpecialRefundOrders(
        String startTime,
        Long pageNo
    ){

        RefundOrderRequest req = buildRefundOrderRequest(startTime,pageNo,2L);
        TbkRelationRefundResponse rsp = getRefundOrder(req);
        return  convertToRefundOrdersList(rsp);

    }

    private static RefundOrderRequest buildRefundOrderRequest(
        String startTime,
        Long pageNo,
        Long bizType
    ){
        RefundOrderRequest request = new RefundOrderRequest();
        request.setPageNo(pageNo);
        request.setPageSize(100L);
        request.setRefundType(1L);
        request.setStartTime(startTime);
        request.setBizType(1L);
        request.setSearchType(bizType);
        return request;
    }

    private static List<RefundOrders> convertToRefundOrdersList(TbkRelationRefundResponse rsp){

        List<RefundOrders> ordersList = new ArrayList<>();
        if(rsp.getResult() != null && rsp.getResult().getData() != null){
            TbkRelationRefundResponse.PageResult pageResult =
                rsp.getResult().getData();
            if(pageResult.getResults() != null){
                for(TbkRelationRefundResponse.Result result: pageResult.getResults()){
                    RefundOrders refundOrders = convertToRefundOrders(result);
                    ordersList.add(refundOrders);
                }
            }
        }

        return ordersList;
    }

    private static TkOrderRsponse buildDefaultTkRsp(){
        TkOrderRsponse ordersResponse = new TkOrderRsponse();
        ordersResponse.setData(null);
        ordersResponse.setHas_next(false);
        ordersResponse.setPosition_index(null);
        return ordersResponse;
    }

    private static Orders convertToOrders(PublisherOrderDto publisherOrderDto){
        Orders orders = new Orders();
        // trade_id
        orders.setTradeId(publisherOrderDto.getTradeId());
        // trade_parent_id
        orders.setTradeParentId(publisherOrderDto.getTradeParentId());
        // num_iid
        orders.setNumIid(publisherOrderDto.getItemId());
        // item_title
        orders.setItemTitle(publisherOrderDto.getItemTitle());
        // item_num
        orders.setItemNum(publisherOrderDto.getItemNum());
        // price
        if(!StringUtils.isEmpty(publisherOrderDto.getItemPrice())){
            orders.setPrice(new BigDecimal(publisherOrderDto.getItemPrice()).setScale(2));
        }
        // pay_price
        if(!StringUtils.isEmpty(publisherOrderDto.getPayPrice())){
            orders.setPayPrice(new BigDecimal(publisherOrderDto.getPayPrice()).setScale(2));
        }
        // seller_nick
        orders.setSellerNick(publisherOrderDto.getSellerNick());
        // seller_shop_title
        orders.setSellerShopTitle(publisherOrderDto.getSellerShopTitle());
//        // commission
//        if(!StringUtils.isEmpty(publisherOrderDto.getTotalCommissionRate())){
//            orders.setCommission(new BigDecimal(publisherOrderDto.getCommission()).setScale(2));
//        }
        // commission_rate
        if(!StringUtils.isEmpty(publisherOrderDto.getTotalCommissionRate())){
            orders.setCommissionRate(new BigDecimal(publisherOrderDto.getTotalCommissionRate()).setScale(2));
        }
        // create_time
        orders.setCreateTime(publisherOrderDto.getTkCreateTime());
        // earning_time
        orders.setEarningTime(publisherOrderDto.getTkEarningTime());
        // tk_status
        orders.setTkStatus(publisherOrderDto.getTkStatus());
//        // tk3rd_type
//        orders.setTk3rdType(publisherOrderDto.getTk3rdType());
        // tk3rd_pub_id
        orders.setTk3rdPubId(publisherOrderDto.getPubId());
        // order_type
        orders.setOrderType(publisherOrderDto.getOrderType());
        // income_rate
        if(!StringUtils.isEmpty(publisherOrderDto.getIncomeRate())){
            BigDecimal incomeRate = new BigDecimal(publisherOrderDto.getIncomeRate());
            orders.setIncomeRate(incomeRate);
        }
        // pub_share_pre_fee
        if(!StringUtils.isEmpty(publisherOrderDto.getPubSharePreFee())){
            BigDecimal pubSharePreFee = new BigDecimal(publisherOrderDto.getPubSharePreFee());
            orders.setPubSharePreFee(pubSharePreFee);
        }
        // subsidy_rate
        if(!StringUtils.isEmpty(publisherOrderDto.getSubsidyFee())){
            BigDecimal subsidyRate = new BigDecimal(publisherOrderDto.getSubsidyFee());
            orders.setSubsidyRate(subsidyRate);
        }
        // subsidy_type
        orders.setSubsidyType(publisherOrderDto.getSubsidyType());
        // terminal_type
        orders.setTerminalType(publisherOrderDto.getTerminalType());
        // auction_category
        orders.setAuctionCategory(publisherOrderDto.getItemCategoryName());
        // site_id
        orders.setSiteId(publisherOrderDto.getSiteId());
        // site_name
        orders.setSiteName(publisherOrderDto.getSiteName());
        // adzone_id
        orders.setAdzoneId(publisherOrderDto.getAdzoneId());
        // adzone_name
        orders.setAdzoneName(publisherOrderDto.getAdzoneName());
        // alipay_total_price
        if(!StringUtils.isEmpty(publisherOrderDto.getAlipayTotalPrice())){
            BigDecimal alipayTotalPrice = new BigDecimal(publisherOrderDto.getAlipayTotalPrice());
            orders.setAlipayTotalPrice(alipayTotalPrice);
        }
        // total_commission_rate
        if(!StringUtils.isEmpty(publisherOrderDto.getTotalCommissionRate())){
            BigDecimal totalCommissionRate = new BigDecimal(publisherOrderDto.getTotalCommissionRate());
            orders.setTotalCommissionRate(totalCommissionRate);
        }
        // total_commission_fee
        if(!StringUtils.isEmpty(publisherOrderDto.getTotalCommissionFee())){
            BigDecimal totalCommissionFee = new BigDecimal(publisherOrderDto.getTotalCommissionFee());
            orders.setTotalCommissionFee(totalCommissionFee);
        }
        // subsidy_fee
        if(!StringUtils.isEmpty(publisherOrderDto.getSubsidyFee())){
            BigDecimal subsidyFee = new BigDecimal(publisherOrderDto.getSubsidyFee());
            orders.setSubsidyFee(subsidyFee);
        }
        // relation_id
        orders.setRelationId(publisherOrderDto.getRelationId());
        // special_id
        orders.setSpecialId(publisherOrderDto.getSpecialId());
        // click_time
        orders.setClickTime(publisherOrderDto.getClickTime());
        // tb_paid_time
        orders.setTbPaidTime(publisherOrderDto.getTbPaidTime());
        // tk_paid_time
        orders.setTkPaidTime(publisherOrderDto.getTkPaidTime());
        // pub_share_fee
        if(!StringUtils.isEmpty(publisherOrderDto.getPubShareFee())){
          BigDecimal pubShareFee = new BigDecimal(publisherOrderDto.getPubShareFee());
          orders.setPubShareFee(pubShareFee);
        }
        // tk_order_role
        orders.setTkOrderRole(publisherOrderDto.getTkOrderRole());
        // pub_share_rate
        if(!StringUtils.isEmpty(publisherOrderDto.getPubShareRate())){
          BigDecimal pubShareRate = new BigDecimal(publisherOrderDto.getPubShareRate());
          orders.setPubShareRate(pubShareRate);
        }
        // refund_tag
        orders.setRefundTag(publisherOrderDto.getRefundTag());
        // tk_total_rate
        if(!StringUtils.isEmpty(publisherOrderDto.getTkTotalRate())){
          BigDecimal tkTotalRate = new BigDecimal(publisherOrderDto.getTkTotalRate());
          orders.setTkTotalRate(tkTotalRate);
        }
        // alimama_rate
        if(!StringUtils.isEmpty(publisherOrderDto.getAlimamaRate())){
          BigDecimal alimamaRate = new BigDecimal(publisherOrderDto.getAlimamaRate());
          orders.setAlimamaRate(alimamaRate);
        }
        // alimama_share_fee
        if(!StringUtils.isEmpty(publisherOrderDto.getAlimamaShareFee())){
          BigDecimal alimamaShareFee = new BigDecimal(publisherOrderDto.getAlimamaShareFee());
          orders.setAlimamaShareFee(alimamaShareFee);
        }
        // flow_source
        orders.setFlowSource(publisherOrderDto.getFlowSource());
        // item_link
        orders.setItemLink(publisherOrderDto.getItemLink());
        // 图片地址
        orders.setItemImg(publisherOrderDto.getItemImg());
        return orders;
    }

    private static RefundOrders convertToRefundOrders(TbkRelationRefundResponse.Result result){
        RefundOrders refundOrders = new RefundOrders();
        refundOrders.setTbTradeParentId(String.valueOf(result.getTbTradeParentId()));
        refundOrders.setTbTradeId(String.valueOf(result.getTbTradeId()));
        refundOrders.setRelationId(result.getRelationId());
        refundOrders.setTk3rdPubId(result.getTk3rdPubId());
        refundOrders.setTkPubId(result.getTkPubId());
        if(!StringUtils.isEmpty(result.getTkSubsidyFeeRefundPub())){
            refundOrders.setTkSubsidyFeeRefundPub(new BigDecimal(result.getTkSubsidyFeeRefundPub()).setScale(2));
        }
        if(!StringUtils.isEmpty(result.getTkCommissionFeeRefundPub())){
            refundOrders.setTkCommissionFeeRefundPub(new BigDecimal(result.getTkCommissionFeeRefundPub()).setScale(2));
        }
        if(!StringUtils.isEmpty(result.getTkSubsidyFeeRefund3rdPub())){
            refundOrders.setTkSubsidyFeeRefund3rdPub(new BigDecimal(result.getTkSubsidyFeeRefund3rdPub()).setScale(2));
        }
        if(!StringUtils.isEmpty(result.getTkCommissionFeeRefund3rdPub())){
            refundOrders.setTkCommissionFeeRefund3rdPub(new BigDecimal(result.getTkCommissionFeeRefund3rdPub()).setScale(2));
        }
        refundOrders.setTkRefundSuitTime(result.getTkRefundSuitTime());
        refundOrders.setTkRefundTime(result.getTkRefundTime());
        refundOrders.setEarningTime(result.getEarningTime());
        refundOrders.setTbTradeCreateTime(result.getTbTradeCreateTime());
        refundOrders.setRefundStatus(result.getRefundStatus());
        refundOrders.setTbAuctionTitle(result.getTbAuctionTitle());
        refundOrders.setTbTradeId(String.valueOf(result.getTbTradeId()));
        refundOrders.setSpecialId(result.getSpecialId());
        if(!StringUtils.isEmpty(result.getTkCommissionFeeRefund3rdPub())){
            refundOrders.setTkCommissionFeeRefund3rdPub(new BigDecimal(result.getTkCommissionFeeRefund3rdPub()).setScale(2));
        }
        return refundOrders;
    }

    // 获取商品详情
    public static TbkItemInfoGetResponse getItemInfo(ItemInfoRequest itemInfoRequest) throws ApiException {

        getAppKeyAndSecred();
        String url = "http://gw.api.taobao.com/router/rest";
        TaobaoClient client = new DefaultTaobaoClient(url,APPKEY, APPSECRET);
        TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
        req.setNumIids(itemInfoRequest.getNum_iids());
        req.setPlatform(itemInfoRequest.getPlatform());
        req.setIp(itemInfoRequest.getIp());
        TbkItemInfoGetResponse rsp = client.execute(req);
        System.out.println(rsp.getBody());
        return rsp;
    }

    // 生成淘口令
    public static String getTpwd(TpwdRequest tpwdRequest){
        try {
            getAppKeyAndSecred();
            String url ="http://gw.api.taobao.com/router/rest";
            TaobaoClient client = new DefaultTaobaoClient(url, APPKEY, APPSECRET);
            TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
            req.setUserId(tpwdRequest.getUser_id());
            req.setText(tpwdRequest.getText());
            req.setUrl(tpwdRequest.getUrl());
            req.setLogo(tpwdRequest.getLogo());
            req.setExt(tpwdRequest.getExt());
            TbkTpwdCreateResponse rsp = client.execute(req);
//            System.out.println(rsp.getBody());
            logger.debug("rsp.getBody is : {}",rsp.getBody());
            return rsp.getData().getModel();
        }catch (Exception ex){
            logger.debug("create tpwd failed, {}",ex);
            throw new TpwdGenerateFailException(ex.getMessage());
        }
    }

    public static Long checkAndGetRelationId(Long relationId,String accessToken){
        if(relationId == null){
            TbkScPublisherInfoSaveResponse rsp = TaobaoUtil.getRelationId(accessToken);
            logger.debug("rsp for relationId is : {}",rsp);
            if(rsp != null && rsp.getData() != null){
                relationId = rsp.getData().getRelationId();
                logger.debug("relationId get is : {}",relationId);
            }
            if(rsp != null && !StringUtils.isEmpty(rsp.getErrorCode())){
                throw new BusinessException("生成渠道id失败:" + rsp.getMsg() + "--"+
                    rsp.getSubMsg(),
                    StatusCode.RELATION_SPECIAL_ID_GENERATE_FAILED);
            }
        }
        return relationId;
    }

    public static Long checkAndGetSpecialId(Long specialId,String accessToken){
        if(specialId == null){
            TbkScPublisherInfoSaveResponse rsp = TaobaoUtil.getSpecialId(accessToken);
            logger.debug("rsp for specialId is : {}",rsp);
            if(rsp != null && rsp.getData() != null){
                specialId = rsp.getData().getSpecialId();
                logger.debug("specialId get is : {}",specialId);
            }
//            if(rsp != null && !StringUtils.isEmpty(rsp.getErrorCode())){
//                throw new BusinessException("生成会员运营id失败:" + rsp.getMsg() + "--"+
//                    rsp.getSubMsg(),
//                    StatusCode.RELATION_SPECIAL_ID_GENERATE_FAILED);
//            }
        }
        return specialId;
    }


    // 生成relationId
     public static TbkScPublisherInfoSaveResponse getRelationId(String sessionKey){
         try {
             return doGetRelationOrSpecialId(sessionKey,RELATION_INVITOR_CODE);
         }catch (ApiException ex){
            logger.debug("获取渠道id失败");
            throw new BusinessException("生成渠道id失败:" +ex.getMessage(),
                StatusCode.RELATION_SPECIAL_ID_GENERATE_FAILED);
         }
     }

     // 生成spedialId
    public static TbkScPublisherInfoSaveResponse getSpecialId(String sessionKey){
        TbkScPublisherInfoSaveRequest req;
        try {
            return doGetRelationOrSpecialId(sessionKey,SPECIAL_INVITOR_CODE);
        }catch (ApiException ex){
            logger.debug("获取渠道id失败");
            throw new BusinessException("生成会员运营id失败:" +ex.getMessage(),
                StatusCode.RELATION_SPECIAL_ID_GENERATE_FAILED);
        }
    }

     private static TbkScPublisherInfoSaveResponse doGetRelationOrSpecialId(
         String sessionKey,String inviterCode) throws ApiException {
         getAppKeyAndSecred();
         TbkScPublisherInfoSaveRequest req;
         TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", APPKEY, APPSECRET);
         req = new TbkScPublisherInfoSaveRequest();
         req.setInviterCode(inviterCode);
         req.setInfoType(1L);
         TbkScPublisherInfoSaveResponse rsp = client.execute(req, sessionKey);
         return rsp;
     }

    /**
     * 获取淘宝授权地址
     * @return
     */
     public static Map<String,String>  openOauth (){
         Map<String,String> url = new HashMap();
         String redirectUri = "https://api.appwangzhan.fltlm.com/H5/";
         String openOauthUrl="https://oauth.taobao.com/authorize?" + "client_id=" + APPKEY +
                 "&response_type=code" + "&redirect_uri=https://api.appwangzhan.fltlm.com/H5/&state=1212&view=wap";
         String taoBaoInformationUrl = "https://oauth.taobao.com/token?client_id=" + APPKEY + "&" +
                 "redirect_uri=https://api.appwangzhan.fltlm.com/H5/&state=1212&view=wap" +
                 "&client_secret=d128f43ef975e70b4594699c53d0d9e7&grant_type=authorization_code&" +
                 "code=";
         url.put("redirectUri",redirectUri);
         url.put("openOauthUrl",openOauthUrl);
         url.put("taoBaoInformationUrl",taoBaoInformationUrl);
         return url;
     }

     public static Object getTaoBaoInformation(String code) throws IOException {
         String url="https://oauth.taobao.com/token";
         Map<String,String> props=new HashMap<>();
         props.put("client_id",APPKEY);
         props.put("client_secret",APPSECRET);
         props.put("redirect_uri","https://api.appwangzhan.fltlm.com/H5/");
         props.put("state","1212");
         props.put("view","wap");
         props.put("grant_type","authorization_code");
         props.put("code",code);

         String sendPost = HttpUtils.sendPost(url, props);
         logger.debug("sendPost is : {}",sendPost);
          Object obj = objectMapper.readValue(sendPost, Object.class);
         logger.debug("obj is : {}",obj);
         return obj;

     }

//     public static void main(String args[]){
//
//         String now = DateUtil.getNowStr();
//         String tmb = DateUtil.getTwentyMinutesBeforeFromNow();
//         now = "2020-06-16 05:40:35";
//         tmb = "2020-06-16 03:20:35";
//         logger.debug("now is and tmb is :{},{}",now,tmb);
//
//         TaobaoUtil.getRelationPaidOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//         TaobaoUtil.getNormalPaidOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//         TaobaoUtil.getSpecialPaidOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//
//         TaobaoUtil.getRelationAcOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//         TaobaoUtil.getNormalAcOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//         TaobaoUtil.getSpecialAcOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//
//         TaobaoUtil.getRelationODOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//         TaobaoUtil.getNormalODOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//         TaobaoUtil.getSpecialODOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//
//         TaobaoUtil.getRelationDoneOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//         TaobaoUtil.getNormalDoneOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//         TaobaoUtil.getSpecialDoneOrders(tmb,now,1L,null);
//         System.out.println("-----------------------------------");
//
//         RefundOrderRequest request = new RefundOrderRequest();
//         request.setPageNo(1L);
//         request.setPageSize(20L);
//         request.setRefundType(1L);
//         request.setStartTime("2019-09-17 10:35:25");
//         request.setBizType(1L);
//         request.setSearchType(1L);
//         TaobaoUtil.getRefundOrder(request);
//     }
}
